<template>
  <div class="sampling-analysis">
    <!-- Filter Card -->
    <div class="search-card">
      <div class="search-section">
        <div class="filter-item">
          <label>调查期</label>
          <el-cascader v-model="queryParams.periodId" :options="periodOptions"
            :props="{ multiple: false, emitPath: false }" placeholder="请选择调查期" clearable class="custom-select" style="width: 220px" />
        </div>

        <div class="filter-item">
          <label>地区筛选</label>
          <el-select v-model="queryParams.regions" placeholder="请选择市级地区（可多选）" clearable filterable multiple
            collapse-tags collapse-tags-tooltip class="custom-select" style="width: 320px">
            <el-option v-for="option in regionOptions" :key="option.value" :label="option.label"
              :value="option.value" />
          </el-select>
        </div>

        <div class="filter-item">
          <label>展示模式</label>
          <el-select v-model="displayMode" placeholder="请选择展示模式" class="custom-select" style="width: 160px">
            <el-option label="企业数量" value="enterprise" />
            <el-option label="岗位数量" value="position" />
            <el-option label="失业率" value="ratio" />
          </el-select>
        </div>

        <div class="filter-actions">
          <el-button type="primary" class="btn-primary-theme" @click="handleQuery" :loading="loading">
            查询
          </el-button>
        </div>
      </div>
    </div>

    <!-- Chart Card -->
    <div class="chart-card" v-if="citySummary.length > 0">
      <div class="card-header">
        <span class="card-title">{{ chartTitle }}</span>
      </div>
      <div class="main-chart-wrapper">
        <div class="chart-with-stats">
          <div ref="chartRef" class="chart-container"></div>
          <div class="chart-stats">
            <div class="stat-item">
              <div class="stat-label">{{ getTotalLabel() }}</div>
              <div class="stat-value">{{ getTotalValue() }}</div>
            </div>
          </div>
        </div>
      </div>

      <div class="city-grid">
        <div v-for="card in cityCards" :key="card.code" class="city-card"
          :class="{ active: activeCityCode === card.code }" @mouseenter="handleCityCardHover(card.code)"
          @mouseleave="handleCityCardHover(null)">
          <div class="city-card__header">
            <div class="city-name">{{ card.name }}</div>
            <div class="city-total">
              <span>{{ getCardLabel() }}</span>
              <strong>{{ formatNumber(getCardValue(card)) }}</strong>
            </div>
          </div>
          <div class="city-card__chart" :ref="el => setCityChartRef(el, card.code)"></div>
        </div>
      </div>
    </div>

    <!-- Table Card -->
    <div class="table-card" v-if="tableData.length > 0">
      <div class="table-header">
        <div class="card-title">详细数据</div>
        <div class="table-controls">
          <el-radio-group v-model="dataViewMode" size="default" class="custom-radio-group">
            <el-radio-button value="overall">整体企业</el-radio-button>
            <el-radio-button value="secondLevel">二级分类</el-radio-button>
          </el-radio-group>

          <!-- City Selector -->
          <el-select v-if="dataViewMode === 'secondLevel'" v-model="selectedCity" placeholder="请选择市级" clearable
            class="custom-select" style="width: 200px; margin-left: 12px;">
            <el-option v-for="city in cityOptions" :key="city.code" :label="city.name" :value="city.code" />
          </el-select>
        </div>
      </div>

      <!-- Overall Table -->
      <el-table v-if="dataViewMode === 'overall'" :data="tableData" class="modern-table"
        :header-cell-style="{ background: '#f8fafc', color: '#475569', fontWeight: '700', fontSize: '13px', height: '56px', textAlign: 'center' }"
        :cell-style="{ textAlign: 'center', padding: '12px 0' }">
        <el-table-column prop="regionName" label="地区" align="center" min-width="160">
          <template #default="{ row }">
            <span class="cell-primary-text">{{ row.regionName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="enterpriseCount" label="企业数量" align="center" min-width="120" />
        <el-table-column label="企业占比" align="center" min-width="120">
          <template #default="{ row }">
            {{ row.percentage.toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column prop="constructionTotal" label="建档期岗位" align="center" min-width="140" />
        <el-table-column prop="investigationTotal" label="调查期岗位" align="center" min-width="140" />
        <el-table-column prop="changeTotal" label="岗位变化" align="center" min-width="120">
          <template #default="{ row }">
            <span :class="row.changeTotal >= 0 ? 'text-success' : 'text-danger'">
              {{ row.changeTotal > 0 ? '+' : '' }}{{ row.changeTotal }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="失业率(%)" align="center" min-width="120">
          <template #default="{ row }">
            <span :class="row.changeRatio >= 0 ? 'text-success' : 'text-danger'">
              {{ row.changeRatio > 0 ? '+' : '' }}{{ row.changeRatio.toFixed(2) }}%
            </span>
          </template>
        </el-table-column>
      </el-table>

      <!-- Second Level Table -->
      <el-table v-if="dataViewMode === 'secondLevel'" :data="filteredSecondLevelData" class="modern-table"
        :header-cell-style="{ background: '#f8fafc', color: '#475569', fontWeight: '700', fontSize: '13px', height: '56px', textAlign: 'center' }"
        :cell-style="{ textAlign: 'center', padding: '12px 0' }">
        <el-table-column prop="parentRegionName" label="市级" align="center" min-width="140" />
        <el-table-column prop="regionName" label="区县" align="center" min-width="160">
          <template #default="{ row }">
            <span class="cell-primary-text">{{ row.regionName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="enterpriseCount" label="企业数量" align="center" min-width="120" />
        <el-table-column label="占市级比例" align="center" min-width="120">
          <template #default="{ row }">
            {{ row.percentage.toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column prop="constructionTotal" label="建档期岗位" align="center" min-width="140" />
        <el-table-column prop="investigationTotal" label="调查期岗位" align="center" min-width="140" />
        <el-table-column prop="changeTotal" label="岗位变化" align="center" min-width="120">
          <template #default="{ row }">
            <span :class="row.changeTotal >= 0 ? 'text-success' : 'text-danger'">
              {{ row.changeTotal > 0 ? '+' : '' }}{{ row.changeTotal }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="失业率(%)" align="center" min-width="120">
          <template #default="{ row }">
            <span :class="row.changeRatio >= 0 ? 'text-success' : 'text-danger'">
              {{ row.changeRatio > 0 ? '+' : '' }}{{ row.changeRatio.toFixed(2) }}%
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- Empty State -->
    <div v-if="!loading && tableData.length === 0" class="empty-card">
      <el-empty description="暂无数据，请选择调查期后查询" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick, watch } from 'vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import dataAnalysisApi from '@/api/dataAnalysis';
import periodApi from '@/api/period';
import { getCities, getTopLevelCity } from '@/utils/regionUtils';

// ... (script logic remains exactly the same) ...
// ==================== 数据定义 ====================

const loading = ref(false);
const chartRef = ref(null);
let chartInstance = null;
const cityChartInstances = new Map();
const cityChartRefs = new Map();

// 查询参数
const queryParams = ref({
  periodId: null,
  regions: [],
});

// 展示模式: 'enterprise' | 'position' | 'ratio'
const displayMode = ref('enterprise');

// 调查期列表
const periodList = ref([]);

const periodOptions = computed(() => {
  const groups = {};

  periodList.value.forEach(period => {
    const name = period.investigateTime || '';
    const yearMatch = name.match(/^(\d{4})/);
    const year = yearMatch ? yearMatch[1] : '其他';

    if (!groups[year]) {
      groups[year] = [];
    }

    let monthLabel = name;
    if (year !== '其他') {
      monthLabel = name.replace(year, '').replace(/^[年-]/, '');
    }

    groups[year].push({
      value: period.periodId,
      label: monthLabel
    });
  });

  return Object.keys(groups)
    .sort((a, b) => b.localeCompare(a))
    .map(year => ({
      value: year,
      label: year === '其他' ? '其他' : `${year}年`,
      children: groups[year]
    }));
});

// 地区级联选择器数据
const regionOptions = ref([]);

// 表格数据
const tableData = ref([]);
const citySummary = ref([]);
const cityCards = ref([]);
// 保存原始后端数据，用于切换展示模式
const rawBackendData = ref([]);
const activeCityCode = ref(null);

// 数据视图模式: 'overall' | 'secondLevel'
const dataViewMode = ref('overall');
// 二级分类数据
const secondLevelTableData = ref([]);
// 选中的市级（用于二级分类视图）
const selectedCity = ref(null);
// 市级选项列表
const cityOptions = ref([]);

const COLOR_PALETTE = [
  '#2563eb',
  '#16a34a',
  '#f97316',
  '#8b5cf6',
  '#ec4899',
  '#0ea5e9',
  '#ca8a04',
  '#ef4444',
  '#14b8a6',
  '#9333ea',
  '#f59e0b',
  '#6366f1',
  '#2dd4bf',
  '#ea580c',
  '#84cc16',
  '#d946ef',
];
const COUNTY_TOP_N = 6;

// ==================== 计算属性 ====================

const chartTitle = computed(() => {
  const titles = {
    enterprise: '企业地区分布',
    position: '岗位地区分布',
    ratio: '失业率分布',
  };
  return titles[displayMode.value] || '数据分布';
});

// ==================== 生命周期 ====================

onMounted(async () => {
  // 加载调查期列表
  await loadPeriodList();

  // 加载市级地区数据
  regionOptions.value = getCities().map(city => ({
    label: city.name,
    value: city.code,
  }));

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  disposeMainChart();
  disposeCityCharts();

  // 移除事件监听
  window.removeEventListener('resize', handleResize);
});

// 监听展示模式变化，重新渲染图表
watch(displayMode, async () => {
  if (rawBackendData.value.length > 0) {
    console.log('🔄 展示模式切换为:', displayMode.value);
    // 使用原始后端数据重新构建图表数据
    const { summary, cards } = buildCityAggregates(rawBackendData.value);
    citySummary.value = summary;
    cityCards.value = cards;

    await nextTick();
    // 重新渲染图表
    renderMainChart();
    renderCityCharts();
  }
});

// ==================== 方法定义 ====================

/**
 * 加载调查期列表
 */
async function loadPeriodList() {
  try {
    // 传递足够大的pageSize获取所有调查期
    const response = await periodApi.getPeriodList({ pageSize: 100 });
    if (response.status === 'success') {
      periodList.value = response.data.list || [];
    }
  } catch (error) {
    console.error('加载调查期列表失败:', error);
    ElMessage.error('加载调查期列表失败');
  }
}

/**
 * 查询按钮点击事件
 */
async function handleQuery() {
  // 参数验证
  if (!queryParams.value.periodId) {
    ElMessage.warning('请选择调查期');
    return;
  }

  loading.value = true;

  try {
    // 构建请求参数
    const params = {
      periodIds: [queryParams.value.periodId],
      statuses: [4],  // 只统计已归档(4)的数据
    };

    // 如果选择了地区，添加到参数中
    if (queryParams.value.regions && queryParams.value.regions.length > 0) {
      params.regions = queryParams.value.regions;
    }

    // 调用API
    const response = await dataAnalysisApi.getSamplingAnalysis(params);

    if (response.status === 'success') {
      const data = response.data || [];

      // 调试：打印后端返回的原始数据
      console.log('🔍 后端返回的原始数据:', JSON.stringify(data, null, 2));

      await updateVisualization(data);

      ElMessage.success('查询成功');
    } else {
      ElMessage.error(response.info || '查询失败');
    }
  } catch (error) {
    console.error('查询失败:', error);
    ElMessage.error('查询失败，请稍后重试');
  } finally {
    loading.value = false;
  }
}

/**
 * 更新图表数据和渲染
 */
async function updateVisualization(data) {
  if (!data || data.length === 0) {
    citySummary.value = [];
    cityCards.value = [];
    tableData.value = [];
    secondLevelTableData.value = [];
    rawBackendData.value = [];
    disposeMainChart();
    disposeCityCharts();
    return;
  }

  // 保存原始后端数据
  rawBackendData.value = data;
  console.log('💾 保存原始后端数据:', data);

  const { summary, cards } = buildCityAggregates(data);
  citySummary.value = summary;
  cityCards.value = cards;

  // 构建表格数据，从原始后端数据中获取岗位字段
  tableData.value = data.map(item => ({
    regionCode: item.regionCode,
    regionName: item.regionName,
    enterpriseCount: item.enterpriseCount || 0,
    percentage: item.percentage || 0,
    constructionTotal: item.constructionTotal || 0,
    investigationTotal: item.investigationTotal || 0,
    changeTotal: item.changeTotal || 0,
    changeRatio: item.changeRatio || 0,
  }));

  // 构建二级分类表格数据
  secondLevelTableData.value = buildSecondLevelTableData(data);

  // 构建市级选项列表
  cityOptions.value = summary.map(item => ({
    code: item.code,
    name: item.name
  }));

  // 默认选中第一个市级
  if (cityOptions.value.length > 0 && !selectedCity.value) {
    selectedCity.value = cityOptions.value[0].code;
  }

  await nextTick();
  renderMainChart();
  await nextTick();
  renderCityCharts();
}

/**
 * 根据展示模式获取显示值
 */
function getDisplayValue(item) {
  switch (displayMode.value) {
    case 'enterprise':
      return Number(item.enterpriseCount) || 0;
    case 'position':
      return Number(item.investigationTotal) || 0;
    case 'ratio':
      return Number(item.changeRatio) || 0;
    default:
      return Number(item.enterpriseCount) || 0;
  }
}

/**
 * 构建市级与县级图表数据
 */
function buildCityAggregates(data) {
  if (!Array.isArray(data)) {
    return { summary: [], cards: [] };
  }

  // 检查数据是否包含children字段（即使为空数组也算）
  const hasChildrenField = data.some(item => item.children !== undefined && item.children !== null);

  // 调试：检查数据结构
  console.log('🔍 hasChildrenField:', hasChildrenField);
  console.log('🔍 数据项示例:', data[0]);

  if (hasChildrenField) {
    const summary = data.map(item => {
      const value = getDisplayValue(item);
      return {
        code: Number(item.regionCode) || item.regionCode,
        name: item.regionName,
        value,
        percentage: Number(item.percentage) || 0,
      };
    });

    const cards = data.map(item => {
      const total = Number(item.enterpriseCount) || 0;
      const constructionTotal = Number(item.constructionTotal) || 0;
      const investigationTotal = Number(item.investigationTotal) || 0;
      const changeTotal = Number(item.changeTotal) || 0;
      const changeRatio = Number(item.changeRatio) || 0;

      let children = item.children;

      // 如果children不存在、为null或为空数组，使用市级数据作为fallback
      if (!Array.isArray(children) || children.length === 0) {
        children = [{
          regionCode: item.regionCode,
          regionName: item.regionName || '未知地区',
          enterpriseCount: total,
          percentage: 100  // 占市级的100%
        }];
        console.log(`ℹ️ 市级 ${item.regionName} 没有二级分类数据，使用市级数据作为fallback`);
      }

      // 调试：输出每个市的children数据
      console.log(`🔍 市级 ${item.regionName} 的children:`, children);

      const chartSeries = buildCountySeries(children.map(child => ({
        name: child.regionName || '未知',
        value: getDisplayValue(child),
        tooltip: child.percentage != null ? `占本市 ${child.percentage}%` : '',
      })));

      console.log(`🔍 市级 ${item.regionName} 的chartSeries:`, chartSeries);

      return {
        code: Number(item.regionCode) || item.regionCode,
        name: item.regionName,
        total,
        constructionTotal,
        investigationTotal,
        changeTotal,
        changeRatio,
        chartSeries,
      };
    });

    return { summary, cards };
  }

  const cityMap = new Map();

  data.forEach(item => {
    const regionCode = Number(item.regionCode) || item.regionCode;
    const cityNode = getTopLevelCity(regionCode) || { code: regionCode, name: item.regionName };
    const cityCode = cityNode.code;

    if (!cityMap.has(cityCode)) {
      cityMap.set(cityCode, {
        code: cityCode,
        name: cityNode.name,
        total: 0,
        counties: [],
      });
    }

    const cityInfo = cityMap.get(cityCode);
    const enterpriseCount = Number(item.enterpriseCount) || 0;
    cityInfo.total += enterpriseCount;
    cityInfo.counties.push({
      code: regionCode,
      name: item.regionName,
      value: enterpriseCount,
    });
  });

  const orderedCities = Array.from(cityMap.values()).sort((a, b) => b.total - a.total);
  const provinceTotal = orderedCities.reduce((sum, city) => sum + city.total, 0);

  return {
    summary: orderedCities.map(city => ({
      code: city.code,
      name: city.name,
      value: city.total,
      percentage: provinceTotal > 0 ? Number(((city.total * 100) / provinceTotal).toFixed(2)) : 0,
    })),
    cards: orderedCities.map(city => ({
      code: city.code,
      name: city.name,
      total: city.total,
      chartSeries: buildCountySeries(city.counties),
    })),
  };
}

/**
 * 生成县级TopN + 其他数据
 */
function buildCountySeries(counties = []) {
  console.log('🔍 buildCountySeries 接收到的数据:', counties);

  const normalized = counties
    .map(item => ({
      name: item.name || item.regionName || '未知地区',
      value: Number(item.value ?? item.enterpriseCount) || 0,
      tooltip: item.tooltip,
    }))
    .filter(item => item && item.name && item.name !== '未知地区');

  const sorted = [...normalized].sort((a, b) => (b.value || 0) - (a.value || 0));
  const top = sorted.slice(0, COUNTY_TOP_N);
  const rest = sorted.slice(COUNTY_TOP_N);

  if (rest.length > 0) {
    top.push({
      name: '其他地区',
      value: rest.reduce((sum, item) => sum + (item.value || 0), 0),
      tooltip: `包含：${rest.map(item => item.name).join('、')}`,
    });
  }

  return top.length > 0 ? top : [{ name: '暂无数据', value: 0 }];
}

/**
 * 计算过滤后的二级分类数据（根据选中的市级）
 */
const filteredSecondLevelData = computed(() => {
  if (!selectedCity.value) {
    return secondLevelTableData.value;
  }

  // 根据选中的市级code过滤数据
  const selectedCityName = cityOptions.value.find(c => c.code === selectedCity.value)?.name;
  if (!selectedCityName) {
    return secondLevelTableData.value;
  }

  return secondLevelTableData.value.filter(
    item => item.parentRegionName === selectedCityName
  );
});

/**
 * 构建二级分类表格数据
 */
function buildSecondLevelTableData(data) {
  if (!Array.isArray(data)) {
    return [];
  }

  const result = [];

  // 遍历每个市级数据
  data.forEach(cityItem => {
    const parentRegionName = cityItem.regionName || '未知市';
    const children = cityItem.children;

    // 如果有children数据，展开成表格行
    if (Array.isArray(children) && children.length > 0) {
      children.forEach(child => {
        result.push({
          parentRegionName: parentRegionName,
          regionCode: child.regionCode,
          regionName: child.regionName || '未知',
          enterpriseCount: Number(child.enterpriseCount) || 0,
          percentage: Number(child.percentage) || 0,
          constructionTotal: Number(child.constructionTotal) || 0,
          investigationTotal: Number(child.investigationTotal) || 0,
          changeTotal: Number(child.changeTotal) || 0,
          changeRatio: Number(child.changeRatio) || 0,
        });
      });
    }
  });

  console.log('🔍 构建的二级分类数据:', result);

  return result;
}

/**
 * 渲染主环图
 */
function renderMainChart() {
  if (!chartRef.value || citySummary.value.length === 0) return;

  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value);
  }

  const option = {
    color: COLOR_PALETTE,
    tooltip: {
      trigger: 'item',
      backgroundColor: '#fff',
      borderColor: '#e5e5e7',
      textStyle: {
        color: '#1d1d1f',
      },
      formatter: ({ data, percent }) => {
        let valueLabel = '';
        switch (displayMode.value) {
          case 'enterprise':
            valueLabel = `企业数：${formatNumber(data.value)}`;
            break;
          case 'position':
            valueLabel = `岗位数：${formatNumber(data.value)}`;
            break;
          case 'ratio':
            valueLabel = `失业率：${data.value.toFixed(2)}%`;
            break;
          default:
            valueLabel = `数值：${formatNumber(data.value)}`;
        }
        return `${data.name}<br/>${valueLabel} (占${percent}%)`;
      },
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      left: 0,
      top: 20,
      bottom: 20,
      textStyle: {
        color: '#86868b',
        fontSize: 13,
      },
    },
    series: [
      {
        name: '市级',
        type: 'pie',
        radius: ['35%', '65%'],
        center: ['65%', '55%'],
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: true,
          formatter: '{b}\n{d}%',
          color: '#1d1d1f',
          fontSize: 12,
        },
        data: citySummary.value,
      },
    ],
  };

  chartInstance.setOption(option);

  chartInstance.off('mouseover');
  chartInstance.off('mouseout');

  chartInstance.on('mouseover', params => {
    activeCityCode.value = params?.data?.code || null;
  });

  chartInstance.on('mouseout', () => {
    activeCityCode.value = null;
  });
}

/**
 * 渲染市级卡片中的小环图
 */
function renderCityCharts() {
  console.log('🔍 开始渲染市级小图，cityCards数量:', cityCards.value.length);

  const activeCodes = new Set(cityCards.value.map(card => card.code));

  Array.from(cityChartInstances.keys()).forEach(code => {
    if (!activeCodes.has(code)) {
      const instance = cityChartInstances.get(code);
      if (instance) {
        instance.dispose();
      }
      cityChartInstances.delete(code);
      cityChartRefs.delete(code);
    }
  });

  cityCards.value.forEach(card => {
    console.log(`🔍 渲染 ${card.name} 的小图，chartSeries:`, card.chartSeries);

    const el = cityChartRefs.get(card.code);
    if (!el) {
      console.warn(`⚠️ ${card.name} 的DOM元素未找到`);
      return;
    }

    let instance = cityChartInstances.get(card.code);
    if (!instance) {
      instance = echarts.init(el);
      cityChartInstances.set(card.code, instance);
    }

    instance.setOption({
      color: COLOR_PALETTE,
      tooltip: {
        trigger: 'item',
        backgroundColor: '#fff',
        borderColor: '#e5e7eb',
        textStyle: { color: '#1d1d1f' },
        formatter: ({ data, percent }) => {
          const detail = data.tooltip ? `<br/><span style="color:#6b7280">${data.tooltip}</span>` : '';
          let valueLabel = '';
          switch (displayMode.value) {
            case 'enterprise':
              valueLabel = `企业数：${formatNumber(data.value)}`;
              break;
            case 'position':
              valueLabel = `岗位数：${formatNumber(data.value)}`;
              break;
            case 'ratio':
              valueLabel = `失业率：${typeof data.value === 'number' ? data.value.toFixed(2) : data.value}%`;
              break;
            default:
              valueLabel = `数值：${formatNumber(data.value)}`;
          }
          return `${card.name}/${data.name}<br/>${valueLabel} (${percent}%)${detail}`;
        },
      },
      series: [
        {
          type: 'pie',
          radius: ['55%', '85%'],
          label: {
            formatter: '{b}\n{d}%',
            fontSize: 10,
            color: '#1d1d1f',
            fontWeight: 400,
          },
          labelLine: {
            length: 15,
            length2: 8,
          },
          data: card.chartSeries,
        },
      ],
    });
  });
}

/**
 * 卡片hover联动主图
 */
function handleCityCardHover(code) {
  activeCityCode.value = code;
  if (!chartInstance) return;

  chartInstance.dispatchAction({ type: 'downplay', seriesIndex: 0 });

  if (code) {
    const target = citySummary.value.find(city => city.code === code);
    if (target) {
      chartInstance.dispatchAction({ type: 'highlight', name: target.name });
    }
  }
}

/**
 * 处理小图容器ref
 */
function setCityChartRef(el, code) {
  if (el) {
    cityChartRefs.set(code, el);
  } else {
    cityChartRefs.delete(code);
  }
}

/**
 * 销毁主图
 */
function disposeMainChart() {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
}

/**
 * 销毁城市小图
 */
function disposeCityCharts() {
  cityChartInstances.forEach(instance => instance.dispose());
  cityChartInstances.clear();
  cityChartRefs.clear();
}

/**
 * 窗口大小变化处理
 */
function handleResize() {
  if (chartInstance) {
    chartInstance.resize();
  }
  cityChartInstances.forEach(instance => instance.resize());
}

/**
 * 统一数字展示
 */
function formatNumber(value) {
  if (value === null || value === undefined) return '-';
  return Number(value).toLocaleString('zh-CN');
}

/**
 * 获取卡片标签
 */
function getCardLabel() {
  const labels = {
    enterprise: '企业数',
    position: '岗位数',
    ratio: '失业率',
  };
  return labels[displayMode.value] || '数值';
}

/**
 * 获取卡片显示值
 */
function getCardValue(card) {
  switch (displayMode.value) {
    case 'enterprise':
      return card.total || 0;
    case 'position':
      return card.investigationTotal || 0;
    case 'ratio':
      // 返回百分比数值（不带%）
      const ratio = card.changeRatio || 0;
      return typeof ratio === 'number' ? ratio.toFixed(2) : '0.00';
    default:
      return card.total || 0;
  }
}

/**
 * 获取总数标签
 */
function getTotalLabel() {
  const labels = {
    enterprise: '企业总数',
    position: '岗位总数',
    ratio: '平均失业率',
  };
  return labels[displayMode.value] || '总数';
}

/**
 * 获取总数值
 */
function getTotalValue() {
  const total = citySummary.value.reduce((sum, item) => sum + (item.value || 0), 0);

  switch (displayMode.value) {
    case 'enterprise':
    case 'position':
      return formatNumber(total);
    case 'ratio':
      // 计算平均失业率
      const avgRatio = citySummary.value.length > 0
        ? total / citySummary.value.length
        : 0;
      return avgRatio.toFixed(2) + '%';
    default:
      return formatNumber(total);
  }
}
</script>

<style scoped lang="scss">
.sampling-analysis {
  /* Search Card */
  .search-card {
    background: #ffffff;
    border-radius: 16px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.02);
    padding: 24px;
    margin-bottom: 24px;
    border: 1px solid rgba(241, 245, 249, 1);
  }

  .search-section {
    display: flex;
    flex-wrap: wrap;
    gap: 24px;
    align-items: flex-end;
  }

  .filter-item {
    display: flex;
    flex-direction: column;
    gap: 8px;

    label {
      font-size: 13px;
      font-weight: 600;
      color: #64748b;
    }
  }

  .filter-actions {
    padding-bottom: 2px;
  }

  /* Cards */
  .chart-card, .table-card, .empty-card {
    background: #ffffff;
    border-radius: 24px;
    box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.03);
    border: 1px solid rgba(241, 245, 249, 1);
    margin-bottom: 24px;
    overflow: hidden;
  }

  .card-header {
    padding: 20px 24px;
    border-bottom: 1px solid #f1f5f9;
  }

  .card-title {
    font-size: 16px;
    font-weight: 700;
    color: #0f172a;
  }

  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid #f1f5f9;

    .card-title {
      margin-bottom: 0;
    }
  }

  .table-controls {
    display: flex;
    align-items: center;
  }

  /* Modern Table */
  .modern-table {
    --el-table-border-color: #f1f5f9;
    --el-table-row-hover-bg-color: #f8fafc;
    --el-table-header-bg-color: #f8fafc;
  }

  .cell-primary-text {
    font-size: 14px;
    font-weight: 600;
    color: #0f172a;
  }

  .text-success { color: #10b981; font-weight: 600; }
  .text-danger { color: #ef4444; font-weight: 600; }

  /* Chart Specifics */
  .main-chart-wrapper {
    padding: 24px;
  }

  .chart-with-stats {
    display: flex;
    align-items: center;
    gap: 40px;
  }

  .chart-container {
    flex: 1;
    height: 400px;
  }

  .chart-stats {
    flex-shrink: 0;
    padding: 32px;
    background: #f8fafc;
    border-radius: 16px;
    min-width: 220px;
    text-align: center;
    border: 1px solid #f1f5f9;
  }

  .stat-label {
    font-size: 14px;
    color: #64748b;
    font-weight: 600;
    margin-bottom: 8px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }

  .stat-value {
    font-size: 40px;
    font-weight: 800;
    color: #4f46e5;
    line-height: 1;
  }

  /* City Grid */
  .city-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
    padding: 0 24px 24px;
  }

  .city-card {
    background: #fff;
    border: 1px solid #e2e8f0;
    border-radius: 16px;
    padding: 20px;
    transition: all 0.2s;

    &:hover, &.active {
      border-color: #818cf8;
      box-shadow: 0 10px 20px -5px rgba(79, 70, 229, 0.15);
      transform: translateY(-2px);
    }
  }

  .city-card__header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: 16px;
  }

  .city-name {
    font-size: 15px;
    font-weight: 700;
    color: #1e293b;
  }

  .city-total {
    text-align: right;
    span {
      display: block;
      font-size: 11px;
      color: #94a3b8;
      font-weight: 600;
      margin-bottom: 2px;
    }
    strong {
      font-size: 18px;
      color: #0f172a;
      font-weight: 700;
    }
  }

  .city-card__chart {
    height: 160px;
  }

  /* Inputs & Buttons */
  .custom-select {
    :deep(.el-input__wrapper) {
      border-radius: 8px;
      box-shadow: 0 0 0 1px #e2e8f0 inset;
      padding: 6px 12px;
      &.is-focus { box-shadow: 0 0 0 2px #818cf8 inset; }
    }
  }

  .btn-primary-theme {
    background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%);
    border: none;
    padding: 10px 24px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
    transition: all 0.2s;
    font-weight: 600;
    height: 40px;

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 8px 20px rgba(79, 70, 229, 0.3);
    }
  }

  .custom-radio-group {
    :deep(.el-radio-button__inner) {
      border-radius: 0;
      border: 1px solid #e2e8f0;
      padding: 8px 20px;
      font-weight: 500;
    }
    :deep(.el-radio-button:first-child .el-radio-button__inner) {
      border-radius: 8px 0 0 8px;
    }
    :deep(.el-radio-button:last-child .el-radio-button__inner) {
      border-radius: 0 8px 8px 0;
    }
    :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
      background-color: #4f46e5;
      border-color: #4f46e5;
      box-shadow: -1px 0 0 0 #4f46e5;
    }
  }

  .empty-card {
    padding: 60px 0;
  }
}
</style>